package com.heima.wemedia.interceptor;


import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WmTokenInterceptor implements HandlerInterceptor {//这里不用交给Spring管理,因为还会建一个过滤器,在过滤器中使用这个拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");//通过请求中的头获取id,token也是从headers中拿的
        if (StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtil.setUser(wmUser);//因为需要一个对象,所以就new一个对象,然后设置用户id
        }
        return true;

//        String userId = request.getHeader("userId");
//          if (StringUtils.isNotBlank(userId)){
//              WmUser wmUser = new WmUser();
//              wmUser.setId(Integer.valueOf(userId));
//              WmThreadLocalUtil.setUser(wmUser);
//          }
//              return true;
//        //return HandlerInterceptor.super.preHandle(request, response, handler);
   }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.remove();
        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
